<script>
const defaultId = '1'

export default {
  name: 'index',
  data() {
    return {
      fileList: [],
      formData: {}
    }
  },
  created() {
    this.$api.logo.get(defaultId).then(res => {
      this.formData.id = res.data.id || defaultId
      if (res.data.imgUrl) {
        this.formData.imgUrl = res.data.imgUrl
        this.fileList = [{
          url: res.data.imgUrl
        }]
      }
    })
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleRemoveChange(file, fileList) {
      this.fileList = fileList
    },
    resetHandler() {
      this.fileList = []
      this.formData = { id: this.formData.id }
    },
    async saveHandler() {
      const data = {
        id: this.formData.id || defaultId
      }
      if (this.fileList.length > 0) {
        const file = this.fileList[0]
        if (file.raw) {
          const formData = new FormData()
          formData.append('file', file.raw)
          const urlRes = await this.$api.fileManage.baseUploadData(
            '/energy-carbon/grass-file/file/upload',
            formData
          )
          data.imgUrl = urlRes.data
        } else {
          data.imgUrl = this.formData.imgUrl || ''
        }
      }
      const res = await this.$api.logo.update(data)
      if (Number(res.code) === 1000) {
        this.$message.success(`保存成功！`)
      }
    }
  }
}
</script>

<template>
  <div class="logo-box">
    <el-form ref="form" :model="formData" label-width="120px">
      <el-form-item label="LOGO" prop="images">
        <el-upload
          ref="upload"
          list-type="picture-card"
          action=""
          :on-change="handleChange"
          :on-remove="handleRemoveChange"
          :file-list="fileList"
          :auto-upload="false"
          :limit="1"
          accept="image/*"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button @click="saveHandler" type="primary" size="medium">保存</el-button>
        <el-button @click="resetHandler" size="medium">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.logo-box {
  background-color: #ffffff;
  padding: 20px 0;
  height: 100%;
}
</style>
